<?php

namespace app\common\model;

use think\Request;
use think\Model;
use think\Db;

class Apply extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 定义字段类型
    protected $type = [
    ];
    protected $append = [
        'type'
    ];

    /**
     * 门店类型
     */
    public function getTypeAttr($value,$data)
    {
        $status = [10 => '小程序申请', 20 => '支付申请', 30 => '入驻申请', 40 => '代理申请', 50 => '实名认证'];
        return $status[$data['apply_type']];
    }

    /**
     * 关联用户详情表
     */
    public function details()
    {
        return $this->hasOne('app\\common\\model\\UserDetail', 'user_id', 'user_id');
    }
    

    /**
     * 获取列表
     */
    public function getList($user_id=0,$apply_type=0)
    {
        // 筛选条件
        $filter = [];
        $apply_type > 0 && $filter['apply_type'] = $apply_type;
        $user_id > 0 && $filter['user_id'] = $user_id;

        // 执行查询
        $list = $this->where($filter)
            ->order('id','desc')
            ->with(['details'])
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);
        return $list;
    }

    /**
     * 获取详情
     */
    public static function detail($id)
    {
        return self::get($id,['details']);
    } 

    /**
     * 获取详情
     */
    public static function getApply($where = [])
    {
        return self::where($where)->with(['details'])->find();
    }

    /**
     * 数据操作
     */
    public function action($data=[],$detail=true)
    {
        // 开启事务
        Db::startTrans();
        try {
            $this->allowField(true)->save($data);
            $this->updateDetail($data,$detail);// 更新资料
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 更新资料
    */ 
    private function updateDetail($data,$detail)
    {
        //是否更新资料，超管提交的数据不更新
        if(!$detail){
            return false;
        }
        if(!isset($data['user_id'])){
            $data['user_id'] = $this->user_id;
        }
        if($detail = UserDetail::getUserDetail($data['user_id'])){
            return $detail->save($data['details']);
        }
        $data['details']['user_id'] = $data['user_id'];
        // 显式指定当前操作为新增操作
        $detail = new UserDetail;
        return $detail->save($data['details']);
    }
}
